<?php

namespace App\Http\Controllers\Api\Web;

use App\Http\Controllers\Common\ApiController;
use App\Models\Article\ArticleInfo;
use App\Models\Article\ArticleOrder;
use App\Models\Constant\Constant;
use App\Models\Setting\SysSetting;
use App\Models\User\MemberOrder;
use App\Models\User\User;
use EasyWeChat\Factory;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;


class IndexController extends ApiController {

    public function buyMember(Request $request) {
        $type = $request->input('type');

        $this->validate($request, [
            'type'=>['required',Rule::in(['first','month','quarter','year'])]
        ],[],[
            'type'=>'会员类型错误！'
        ]);

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user)) return responseFail('无效用户');

        if($type=='first' && $user->isBuyFirst()) {
            return responseFail('您已经购买过首试了！');
        }

        $order_number = time().uniqid();
        $price = SysSetting::where('key',$type)->first()->val??138;
        $fee = env('APP_ENV','test')=='test'?1:$price * 100;

        if($user->is_member==1){
            $fee =ceil( $fee*Constant::DISCOUNT);
        }

        $order = MemberOrder::create(['user_id'=>$user->id,'order_number'=>$order_number,'fee'=>($fee/100),'type'=>$type]);

        $config = config('wechat.default');
        $app = Factory::payment($config);
        $result = $app->order->unify([
            'body' => '池塘边素材-会员充值',
            'out_trade_no' => $order_number,
            'total_fee' => $fee,
            'trade_type' => 'NATIVE', // 请对应换成你的支付方式对应的值类型
            'openid' => $user->open_id,
        ]);

        if($result['return_code'] == 'SUCCESS'){
            $code_url = $result['code_url'];
            return responseSuccess(compact('code_url','order_number'));
        }else{
            return responseFail('支付失败，请联系客服！');
        }
    }

    public function exBuyMember(Request $request) {
        $type = $request->input('type');

        $this->validate($request, [
            'type'=>['required',Rule::in(['exfirst','exmonth','exquarter','exyear'])]
        ],[],[
            'type'=>'会员类型错误！'
        ]);

        $token = $request->header('token');
        $id = checkJWT($token)['id'];
        $user = User::where(compact('id'))->first();
        if(empty($user)) return responseFail('无效用户');

        if($type=='exfirst' && $user->isExBuyFirst()) {
            return responseFail('您已经购买过'.Constant::ExFirst.'次首试了！');
        }

        $order_number = time().uniqid();
        $price = SysSetting::where('key',$type)->first()->val??138;
        $fee = env('APP_ENV','test')=='test'?1:$price * 100;

        if($user->ex_is_member==1){
            $fee =ceil( $fee*Constant::DISCOUNT);
        }

        $order = MemberOrder::create(['user_id'=>$user->id,'order_number'=>$order_number,'fee'=>($fee/100),'type'=>$type,'is_auto'=>3]);

        $config = config('wechat.default');
        $app = Factory::payment($config);
        $result = $app->order->unify([
            'body' => '池塘边文库-会员充值',
            'out_trade_no' => $order_number,
            'total_fee' => $fee,
            'trade_type' => 'NATIVE', // 请对应换成你的支付方式对应的值类型
            'openid' => $user->open_id,
        ]);

        if($result['return_code'] == 'SUCCESS'){
            $code_url = $result['code_url'];
            return responseSuccess(compact('code_url','order_number'));
        }else{
            return responseFail('支付失败，请联系客服！');
        }
    }

    /**
     * 购买文档两个网站是并用的
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function buyArticle(Request $request) {
        $id = $request->input('id');
        $from = $request->header('from');
        $record = ArticleInfo::where(compact('id'))->first();
        if(empty($record)) return responseFail('未查找到有效文档！');
        $is_auto = 1;
        if($from==Constant::FROM_CODE)
            $is_auto = 3;

        $token = $request->header('token');
        $userId = checkJWT($token)['id'];
        $user = User::where(['id'=>$userId])->first();
        if(empty($user)) return responseFail('未查找到有效用户！');

        $order_number = time().uniqid();
        $price = $record->price;
        $fee = env('APP_ENV','test')=='test'?1:$price * 100;

        $order = ArticleOrder::create(['article_id'=>$id,'user_id'=>$user->id,'order_number'=>$order_number,'fee'=>($fee/100),'is_auto'=>$is_auto]);

        $config = config('wechat.default');
        $app = Factory::payment($config);
        $result = $app->order->unify([
            'body' => '池塘边素材-文档购买',
            'out_trade_no' => $order_number,
            'total_fee' => $fee,
            'trade_type' => 'NATIVE', // 请对应换成你的支付方式对应的值类型
            'openid' => $user->open_id,
            'notify_url'=> env('APP_URL').'/wx/payCallbackForArticle'
        ]);
        if($result['return_code'] == 'SUCCESS'){
            $code_url = $result['code_url'];
            return responseSuccess(compact('code_url','order_number'));
        }else{
            return responseFail('支付失败，请联系客服！');
        }


    }
}
